package grpcx

import (
	"common"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
	"google.golang.org/grpc/credentials/insecure"
	"path/filepath"
)

type (
	GrpcCaller func(conn *grpc.ClientConn) error
)

// NewCertServer 创建带证书的grpc服务
func NewCertServer(certFile, keyFile string) *grpc.Server {
	cert, err := filepath.Abs(certFile)
	if err != nil {
		panic(err)
	}
	key, err := filepath.Abs(keyFile)
	if err != nil {
		panic(err)
	}
	creds, err := credentials.NewServerTLSFromFile(cert, key)
	if err != nil {
		panic(err)
	}
	return grpc.NewServer(grpc.Creds(creds))
}

// NewNoCertConn 没有证书的grpc连接
func NewNoCertConn(serverName string) (*grpc.ClientConn, error) {
	return grpc.Dial(
		common.ConsulSerUrl(serverName),
		grpc.WithTransportCredentials(insecure.NewCredentials()),
	)
}

// NewNoCertConnWithCaller 带回调的远程调用
func NewNoCertConnWithCaller(serverName string, caller GrpcCaller) error {
	conn, err := NewNoCertConn(serverName)
	if err != nil {
		return err
	}
	defer conn.Close()
	return caller(conn)
}
